﻿#include "pinyincustom.h"
#include "frminput2019.h"

PinYinCustom::PinYinCustom(QObject *parent) : QObject(parent)
{
    input = 0;
}

void PinYinCustom::setInput(frmInput2019 *input)
{
    this->input = input;
}

void PinYinCustom::readChinese()
{
    //载入本地优先词库
    input->selectKey.clear();
    input->selectValue.clear();
    QFile fileSelect(input->dbPath + "/chinese_select.txt");
    if (fileSelect.open(QFile::ReadOnly | QFile::Text)) {
        while (!fileSelect.atEnd()) {
            QString line = fileSelect.readLine();
            line.replace("\n", "");
            QStringList list = line.split(" ");
            input->selectKey << list.at(0);
            input->selectValue << list.at(1);
        }

        fileSelect.close();
    }

    //载入本地自定义词库
    input->userKey.clear();
    input->userValue.clear();
    QFile fileUser(input->dbPath + "/chinese_user.txt");
    if (fileUser.open(QFile::ReadOnly | QFile::Text)) {
        while (!fileUser.atEnd()) {
            QString line = fileUser.readLine();
            line.replace("\n", "");
            QStringList list = line.split(" ");
            input->userKey << list.at(0);
            input->userValue << list.at(1);
        }

        fileUser.close();
    }
}

void PinYinCustom::saveChinese(const QString &value, const QString &pinyin)
{
    //当前不处于中文输入状态不用处理 回车键取得拼音也不用保存
    if (input->inputType != "chinese" || value.isEmpty() || input->lastText.isEmpty() || value == pinyin) {
        return;
    }

    //将当前选中汉字作为优先词库插入文件
    //如果当前字母已经在优先词库文件,则更新该字母对应的汉字
    int index = input->selectKey.indexOf(pinyin);
    if (index >= 0) {
        QStringList temp;
        QString chineses = input->selectValue.at(index);
        QStringList list = chineses.split("|");

        //已经存在则当前不需要加入,后面直接插入到最前面即可
        bool exist = list.contains(value);
        foreach (QString str, list) {
            if (exist && str == value) {
                continue;
            }
            if (!str.isEmpty()) {
                temp << str;
            }
        }

        temp.insert(0, value);
        input->selectValue[index] = temp.join("|");
    } else {
        input->selectKey << pinyin;
        input->selectValue << value;
    }

    QStringList list;
    int count = input->selectKey.count();
    for (int i = 0; i < count; i++) {
        list << QString("%1 %2").arg(input->selectKey.at(i)).arg(input->selectValue.at(i));
    }

    //重新保存优先词库文件
    QString data = list.join("\n");
    QFile fileSelect(input->dbPath + "/chinese_select.txt");
    if (fileSelect.open(QFile::WriteOnly | QFile::Text)) {
        fileSelect.write(data.toUtf8());
        fileSelect.close();
    }
}
